<template>
  <Tab @goBack="goBack" :tabs="tabs" :current="current">
    <div slot="index">
      <el-form :inline="true" label-width="80px">
        <el-form-item label="查询">
          <el-input
            v-model="queryParams.mobile"
            placeholder="真实姓名/手机号码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="daterange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleInsert">新增</el-button>
        </el-form-item>

      </el-form>
      <el-table v-loading="loading" :data="postList" @sort-change="sortChange">
        <el-table-column label="用户编号" align="center" prop="idNo">
          <template slot-scope="scope">
            <el-link title="查看详情" type="primary"
                     @click="handleUserInfo(scope.row)">{{scope.row.idNo}}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="真实姓名" align="center" prop="nickname"/>
        <el-table-column label="身份证号码" align="center" prop="idcard">
          <template slot-scope="scope">
            <el-popover placement="top-start" title="身份证号码" width="250" trigger="hover">
              <div>{{scope.row.idcard}}</div>
              <span slot="reference" v-if="scope.row.idcard">{{ scope.row.idcard.substr(0,10)+'...' }}</span>
              <span slot="reference" v-else class="text-info">无</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="mobile"/>
        <el-table-column label="渠道分成(%)" align="center" prop="promotionScale">
          <template slot-scope="scope">
            <span>{{scope.row.promotionScale*100|currencyFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column label="渠道会员数" align="center" prop="num">
          <template slot-scope="scope">
            <span>{{scope.row.num||0}}</span>
          </template>
        </el-table-column>
        <el-table-column label="总收益" align="center" prop="amount">
          <template slot-scope="scope">
            <span>{{scope.row.amount|currencyFilter}}</span>
          </template>
        </el-table-column>

        <el-table-column label="上月收益" align="center" prop="last">
          <template slot-scope="scope">
            <span>{{scope.row.last|currencyFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column label="本月收益" align="center" prop="now">
          <template slot-scope="scope">
            <span>{{scope.row.now|currencyFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column label="余额" align="center" prop="balance">
          <template slot-scope="scope">
            <el-link title="查看详情" type="primary"
                     @click="handleCurrent('asset',scope.row)"> <span>{{scope.row.balance|currencyFilter}}</span>
            </el-link>

          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createtime" :show-tooltip-when-overflow="true"/>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <div>
              <el-link type="primary" @click="handleUpdate(scope.row)">编辑</el-link>
              <el-link type="primary" @click="handleCurrent('income',scope.row)">收益明细</el-link>
              <el-link type="primary" @click="handleCurrent('recommend',scope.row)">推荐明细</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <UserInfo :show="userInfoShow" @close="handleUserInfoClose" v-if="userItem" :item="userItem"></UserInfo>

      <el-dialog :title="title" :visible.sync="open" width="600px" :close-on-click-modal="false">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">

          <el-form-item label="手机号码" prop="mobile">
            <el-select
              :disabled="!!form.id"
              @change="handleChange"
              style="width: 300px;"
              v-model="form.userId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入手机号码查询"
              :remote-method="remoteMethod"
              :loading="selectLoading">
              <el-option
                v-for="item in options"
                :key="item.idNo"
                :label="item.nickname+'-'+roleFormat(item)+'-'+item.mobile"
                :value="item.id">
                <span style="float: left">{{ item.mobile }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ roleFormat(item) }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="真实姓名" prop="nickname">
            <el-input v-model="form.nickname" placeholder="请输入真实姓名"/>
          </el-form-item>

          <el-form-item label="身份证号码" prop="idcard">
            <el-input v-model="form.idcard" placeholder="请输入身份证号码"/>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入密码"/>
            <span v-if="form.id" class="text-navy">不输入则表示不修改密码</span>
          </el-form-item>
          <el-form-item label="渠道奖励比例" prop="promotionScale">
            <el-input-number style="width: 60%" v-model="form.promotionScale" :step="0.001" :max="0.005" :min="0"
                             placeholder="请输入渠道奖励比例"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="addLoading" @click.native.prevent="submitForm">
            <span v-if="!addLoading">提 交</span>
            <span v-else>提 交 中...</span>
          </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
    <div slot="recommend">
      <Recommend :row="row" :roleOptions="roleOptions"></Recommend>
    </div>
    <div slot="income">
      <Income :row="row"></Income>
    </div>
    <div slot="asset">
      <Asset :row="row"></Asset>
    </div>
  </Tab>

</template>

<script>
  import Tab from "@/components/Tab";
  import Recommend from "./recommend";
  import Income from "./income";
  import {userList, addChannelUser, channelUserList, editChannelUser} from "@/api/channel/user";
  import UserInfo from '@/views/components/user';
  import mixin from '@/views/components/user/mixin';
  import Asset from './asset';

  export default {
    mixins: [mixin],
    components: {Asset, Tab, Recommend, Income, UserInfo},
    data() {
      return {
        title: '',
        open: false,
        row: undefined,
        addLoading: false,
        selectLoading: false,
        userInfoShow:false,
        form: {
          userId: undefined,
          idNo: undefined,
          nickname: undefined,
          idcard: undefined,
          password: undefined,
          mobile: undefined,
          username: undefined,
          promotionScale: 0
        },
        rules: {
          password: [
            {min: 6, max: 16, message: '长度必须在(6-16)字符', trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入手机号码', trigger: 'blur'},
            {max: 20, message: '长度最大为20字符', trigger: 'blur'}
          ],
          nickname: [
            {required: true, message: '请输入真实姓名', trigger: 'blur'},
            {max: 50, message: '长度最大为50字符', trigger: 'blur'}
          ],
          idcard: [
            {required: true, message: '请输入身份证号码', trigger: 'blur'},
            {max: 18, message: '长度最大为18字符', trigger: 'blur'}
          ],
        },
        roleOptions: [],
        options: undefined,
        total: 0,
        loading: false,
        current: 'index',
        daterange: '',
        queryParams: {
          mobile: '',
          pageNum: 1,
          pageSize: 10
        },
        postList: [],
        tabs: [
          {index: 'index', name: ''}, {index: 'recommend', name: '推荐明细'}, {index: 'income', name: '收益明细'},
          {index:'asset',name:'资产记录'}
        ],

      }
    },
    created() {
      this.getDicts("yy_user_role").then(response => {
        this.roleOptions = response.data;
      });
      this.getList();
    },
    methods: {
      handleUpdate(row) {
        this.reset();
        this.form = {
          id: row.id,
          userId: row.nickname + '-' + this.roleFormat(row) + '-' + row.mobile + '2',
          idNo: row.idNo,
          nickname: row.nickname,
          idcard: row.idcard,
          password: undefined,
          mobile: row.mobile,
          username: undefined,
          promotionScale: row.promotionScale
        };


        //this.handleChange(row.userId);
        this.title = '编辑';
        this.open = true;
      },
      handleInsert() {
        this.reset();
        this.title = '新增';
        this.open = true;
      },
      roleFormat(row, column) {
        return this.selectDictLabel(this.roleOptions, row.role);
      },
      remoteMethod(query) {
        if (query && query.trim()) {
          this.selectLoading = true;
          userList({mobile: query}).then(response => {
            console.log(response);
            this.options = response.data;
            this.selectLoading = false;
          });
        }
      },
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.addLoading = true;
            if (this.form.id) {
              this.form.userId = undefined;
              editChannelUser(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("编辑渠道用户成功");
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
                this.open = false;
              });
            } else {
              addChannelUser(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("添加渠道用户成功");
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
                this.open = false;
              });
            }

          }
        });
      },
      reset() {
        this.addLoading = false;
        this.options = [];
        this.form = {
          id: undefined,
          userId: undefined,
          idNo: undefined,
          nickname: undefined,
          idcard: undefined,
          password: undefined,
          mobile: undefined,
          username: undefined,
          promotionScale: 0
        };
        this.resetForm("form");
      },
      cancel() {
        this.open = false;
        this.reset();
      },
      handleChange(id) {
        let item = this.options.find(obj => obj.id === id);
        this.$set(this.form, 'mobile', item.mobile);
        this.$set(this.form, 'username', item.nickname);
        if (item.tfsUserAuth) {
          this.$set(this.form, 'nickname', item.tfsUserAuth.custName);
          this.$set(this.form, 'idcard', item.tfsUserAuth.idNo);
        }
      },
      handleCurrent(str, data) {
        this.row = data;
        this.current = str;
      },
      goBack(message) {
        this.current = 'index';
      },
      sortChange(params) {
        if (params.prop === 'createtime') {
          let createtime = 'T1.createtime';
          if (params.order === 'ascending') {
            this.queryParams.orderByColumn = createtime + ' ASC';
          } else {
            this.queryParams.orderByColumn = createtime + ' DESC';
          }
        }
        this.getList();
      },
      handleQuery() {
        this.getList();
      },
      getList() {
        this.loading = true;
        channelUserList(this.queryDateRange(this.queryParams, this.daterange)).then(response => {
          this.postList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    }
  }
</script>

<style scoped>

</style>
